/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年03月01日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int len = heights.size();
        if( len == 0 )
            return 0;

        int maxarea = 0;
        int index = 0;
        stack <int> s;
        s.push(0);
        for(int i = 1; i < len; i++){
            index = s.top();
            while( heights[index] > heights[i] ){
                maxarea = max(maxarea, (i - index)*heights[index]);
                s.pop();
                if( s.empty() ){
                    break;
                }

                index = s.top();
            }
            
            s.push(i);
        }

        index = s.top();
        s.pop();
        while( !s.empty() ){
            maxarea = max(maxarea, (len - index) * heights[index]);
            index = s.top();
            s.pop();
        }

        maxarea = max(maxarea, len * heights[index]);

        return maxarea;
    }
};

